import { resetRouter, constantRoutes, asyncRouterMap } from '@/router';

function hasPermission(role, route) {
    if (route.meta && route.meta.role) {
        return  route.meta.role.indexOf(role) >= 0
    } else {
        return true
    }
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
    const res = []
    routes.forEach(route => {
        const tmp = {...route }
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })
    return res
}
const state = {
    routes: constantRoutes,
    addRoutes: []
}
const mutations = {
    SET_ROUTERS: (state, routes) => {
        state.addRoutes = routes;
        state.routes = constantRoutes.concat(routes);
    }
}
const actions = {
    GenerateRoutes({ commit }, data) {
        return new Promise(resolve => {
            let accessedRoutes
            let role = data.hasGetUserRoles
            
            if (role === 'admin') {
                accessedRoutes = asyncRouterMap || []
            } else {
                accessedRoutes = filterAsyncRoutes(asyncRouterMap, role)
            }
            commit('SET_ROUTERS', accessedRoutes);
            resolve(accessedRoutes);
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
};